﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Windows;
using System.Windows.Markup;

namespace Tanmia.Basis.WPF
{
    public abstract class ExtendedMarkupExtension : MarkupExtension
    {
        public PropertyPath Path { get; set; }

        protected T GetService<T>(IServiceProvider serviceProvider)
        {
            return (T)serviceProvider.GetService(typeof(T));
        }

        protected T GetCustomAttribute<T>(PropertyDescriptor propertyDesc)
            where T : Attribute
        {
            foreach (Attribute attr in propertyDesc.Attributes)
                if (typeof(T) == attr.GetType())
                    return attr as T;

            return null;
        }

        protected T GetCustomAttribute<T>(PropertyInfo propInfo)
            where T : Attribute
        {
            return DisplayAttribute.GetCustomAttribute(propInfo, typeof(T)) as T;
        }

        protected PropertyInfo GetPropertyByPath(object obj, string propertyPath)
        {
            if (obj == null)
                return null;

            Type type = obj.GetType();

            PropertyInfo propertyInfo = null;
            foreach (var part in propertyPath.Split('.'))
            {

                // On subsequent iterations use the type of the property
                if (propertyInfo != null)
                    type = propertyInfo.PropertyType;

                // Get the property at this part
                propertyInfo = type.GetProperty(part);

                // Not found
                if (propertyInfo == null)
                    return null;

                // Can't navigate into indexer
                if (propertyInfo.GetIndexParameters().Length > 0)
                    return null;

            }   // foreach

            return propertyInfo;

        }
    }
}
